'use client'

import { useMemo } from 'react'
import { ToolCard } from '@/components/tools/tool-card'
import { Search, Filter } from 'lucide-react'

interface Tool {
  id: string
  title: string
  description: string
  url: string
  image?: string
  categoryId: string
  userId: string
  status: string
  isDeployed?: boolean
  createdAt: string
  updatedAt: string
  category: {
    id: string
    name: string
    icon: string
  }
  user: {
    name: string
    avatar?: string
  }
  _count: {
    reviews: number
    favorites: number
  }
}

interface SearchResultsProps {
  tools: Tool[]
  searchQuery: string
  categoryFilter: string
  loading?: boolean
}

export function SearchResults({ 
  tools, 
  searchQuery, 
  categoryFilter, 
  loading = false 
}: SearchResultsProps) {
  
  // 搜索和筛选逻辑
  const filteredTools = useMemo(() => {
    let filtered = tools.filter(tool => tool.status === 'APPROVED')

    // 按搜索关键词筛选
    if (searchQuery.trim()) {
      const query = searchQuery.toLowerCase().trim()
      filtered = filtered.filter(tool => 
        tool.title.toLowerCase().includes(query) ||
        tool.description.toLowerCase().includes(query) ||
        tool.category.name.toLowerCase().includes(query) ||
        tool.user.name.toLowerCase().includes(query)
      )
    }

    // 按分类筛选
    if (categoryFilter) {
      filtered = filtered.filter(tool => tool.categoryId === categoryFilter)
    }

    // 按相关性排序（如果有搜索关键词）
    if (searchQuery.trim()) {
      const query = searchQuery.toLowerCase().trim()
      filtered.sort((a, b) => {
        const aScore = getRelevanceScore(a, query)
        const bScore = getRelevanceScore(b, query)
        return bScore - aScore
      })
    } else {
      // 默认按创建时间排序
      filtered.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
    }

    return filtered
  }, [tools, searchQuery, categoryFilter])

  // 计算相关性得分
  const getRelevanceScore = (tool: Tool, query: string): number => {
    let score = 0
    const title = tool.title.toLowerCase()
    const description = tool.description.toLowerCase()
    
    // 标题完全匹配得分最高
    if (title === query) score += 100
    // 标题开头匹配
    else if (title.startsWith(query)) score += 80
    // 标题包含
    else if (title.includes(query)) score += 60
    
    // 描述匹配
    if (description.includes(query)) score += 30
    
    // 分类匹配
    if (tool.category.name.toLowerCase().includes(query)) score += 20
    
    // 用户名匹配
    if (tool.user.name.toLowerCase().includes(query)) score += 10
    
    return score
  }

  // 高亮搜索关键词
  const highlightText = (text: string, query: string) => {
    if (!query.trim()) return text
    
    const regex = new RegExp(`(${query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi')
    const parts = text.split(regex)
    
    return parts.map((part, index) => 
      regex.test(part) ? (
        <mark key={index} className="bg-yellow-200 px-1 rounded">
          {part}
        </mark>
      ) : part
    )
  }

  if (loading) {
    return (
      <div className="space-y-4">
        {Array.from({ length: 6 }).map((_, i) => (
          <div key={i} className="animate-pulse">
            <div className="bg-white rounded-lg border border-gray-200 p-6">
              <div className="h-4 bg-gray-200 rounded w-1/4 mb-2"></div>
              <div className="h-3 bg-gray-200 rounded w-3/4 mb-4"></div>
              <div className="flex gap-2">
                <div className="h-8 bg-gray-200 rounded w-20"></div>
                <div className="h-8 bg-gray-200 rounded w-20"></div>
              </div>
            </div>
          </div>
        ))}
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* 搜索结果统计 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2 text-sm text-gray-600">
          <Search className="h-4 w-4" />
          <span>
            找到 <span className="font-semibold text-gray-900">{filteredTools.length}</span> 个工具
            {searchQuery && (
              <span> 包含 "<span className="font-semibold">{searchQuery}</span>"</span>
            )}
            {categoryFilter && (
              <span> 在分类中</span>
            )}
          </span>
        </div>
      </div>

      {/* 搜索结果 */}
      {filteredTools.length === 0 ? (
        <div className="text-center py-12">
          <div className="mx-auto h-24 w-24 text-gray-400 mb-4">
            <Search className="h-full w-full" />
          </div>
          <h3 className="text-lg font-medium text-gray-900 mb-2">
            没有找到相关工具
          </h3>
          <p className="text-gray-500 mb-4">
            {searchQuery ? (
              <>尝试使用不同的关键词或</>
            ) : (
              <>尝试</>
            )}
            调整筛选条件
          </p>
          {(searchQuery || categoryFilter) && (
            <button
              onClick={() => window.location.href = '/'}
              className="text-blue-600 hover:text-blue-700 font-medium"
            >
              查看所有工具
            </button>
          )}
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {filteredTools.map((tool) => (
            <div key={tool.id}>
              <ToolCard 
                tool={{
                  ...tool,
                  title: searchQuery ? highlightText(tool.title, searchQuery) : tool.title,
                  description: searchQuery ? highlightText(tool.description, searchQuery) : tool.description
                }} 
              />
            </div>
          ))}
        </div>
      )}
    </div>
  )
}
